#include "StdAfx.h"
#include "ChatRoom.h"
#include "Protocol.h"
#include <algorithm>
#include "ChatServerDoc.h"

CChatRoom::CChatRoom(void)
{
}

CChatRoom::~CChatRoom(void)
{
}

void CChatRoom::SetRoomName( CChatServerDoc& doc, const TCHAR* pRoomName )
{
	m_pChatServerDoc = &doc;
	m_roomName = pRoomName;
}

CString& CChatRoom::GetRoomName()
{
	return m_roomName;
}

void CChatRoom::EnterRoom( const RakNetGUID& userGuid )
{
	m_joinedUserContainer.push_back(userGuid);
}

void CChatRoom::ExitRoom( const RakNetGUID& userGuid )
{
	JOINED_USER_CONTAINER::iterator it = std::find(m_joinedUserContainer.begin(), m_joinedUserContainer.end(), userGuid);

	if (it != m_joinedUserContainer.end())
	{
		m_joinedUserContainer.erase(it);
	}
}

void CChatRoom::SendMessageForJoiningUserToEvenryOne( const RakNetGUID& joiningUserGuid )
{
	RakNet::BitStream writeBitStream;
	writeBitStream.Write(JoinChatRoomAck().GetMessageID());
	
	writeBitStream.Write(true);
	writeBitStream.Write((BYTE)1);
	writeBitStream.Write(joiningUserGuid);

	for each(const RakNetGUID& joinedUser in m_joinedUserContainer)
	{
		if (joinedUser == joiningUserGuid)
		{
			continue;
		}

		m_pChatServerDoc->Send(&writeBitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, joinedUser, false);
	}
}

void CChatRoom::SendMessageForJoinedUsersToJoiningUser( const RakNetGUID& joiningUserGuid )
{
	RakNet::BitStream writeBitStream;
	writeBitStream.Write(JoinChatRoomAck().GetMessageID());

	writeBitStream.Write(true);
	writeBitStream.Write((BYTE)m_joinedUserContainer.size());

	for each(const RakNetGUID& joinedUser in m_joinedUserContainer)
	{
		writeBitStream.Write(joinedUser);
	}
	
	m_pChatServerDoc->Send(&writeBitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, joiningUserGuid, false);
	
}

bool CChatRoom::IsExistUser( const RakNetGUID& userGuid )
{
	JOINED_USER_CONTAINER::iterator it = std::find(m_joinedUserContainer.begin(), m_joinedUserContainer.end(), userGuid);

	if (it == m_joinedUserContainer.end())
	{
		return false;
	}

	return true;
}